package com.corecmd.tcloud.tcimserver.shiro;

import com.corecmd.tcloud.tcimserver.utils.AuthtokenCheckUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.web.filter.authz.AuthorizationFilter;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author : tianshaojiao
 * @version : 1.0
 * @apiNote :
 * @date : 2020/6/21
 * @copyright :
 */
@Slf4j
public class AuthtokenCheckFilter extends AuthorizationFilter {
    @Override
    protected boolean isAccessAllowed(ServletRequest servletRequest, ServletResponse servletResponse, Object mappedValue) throws Exception {
        HttpServletRequest request = (HttpServletRequest)servletRequest;
        HttpServletResponse response = (HttpServletResponse)servletResponse;
        if (request.getMethod().equals(RequestMethod.OPTIONS.name())) {
            log.info("OPTIONS请求不做拦截操作");
            return true;
        }
        String authToken = request.getHeader("authToken");
        log.info("校验Token:{} 是否有效!",authToken);
        boolean isAllowAccess = false;
        try {
            boolean isTokenExpired = AuthtokenCheckUtil.check(authToken,request,response);
            isAllowAccess = !isTokenExpired;
        } catch (Exception e) {
            log.info("过滤器校验token:{}异常",authToken,e);
        }
        log.info("过滤器Token校验是否通过：{}",isAllowAccess);
        return isAllowAccess;
    }

    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws IOException {
        log.info("认证不通过时走这里");
        HttpServletResponse httpResp = (HttpServletResponse)response;
        HttpServletRequest httpReq = (HttpServletRequest)request;

        /*系统重定向会默认把请求头清空，这里通过拦截器重新设置请求头，解决跨域问题*/
        httpResp.addHeader("Access-Control-Allow-Origin", httpReq.getHeader("Origin"));
        httpResp.addHeader("Access-Control-Allow-Headers", "*");
        httpResp.addHeader("Access-Control-Allow-Methods", "*");
        httpResp.addHeader("Access-Control-Allow-Credentials", "true");
        this.saveRequestAndRedirectToLogin(request, response);
        return false;
    }
}
